//
//  Emoticon.swift
//  01-表情键盘
//
//  Created by 陈伟 on 15/10/23.
//  Copyright © 2015年 陈伟. All rights reserved.
//

import UIKit

//可重用标示符
let ReuseCollectionCellID = "ReuseCollectionCellID"

class EmoticonView: UIView {
    
    var callBack: (EmoticonModel) -> ()
    private lazy var packages = EmoticonManager.sharedManager.emoticonList
    //懒加载选项
    private lazy var bottomBar: UIToolbar = UIToolbar()
    
    //懒加载conllection
    private lazy var emoticonList: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: emoticonLayout())
//        let layout = UICollectionViewFlowLayout()
//        let row: CGFloat = 7
//        let lie: CGFloat = 3
//        layout.minimumLineSpacing = 0
//        layout.minimumInteritemSpacing = 0
//        let w = UIScreen.mainScreen().bounds.width / row
//        layout.itemSize = CGSize(width: w, height: w)
////        UIEdgeInsets(top: 6.9, left: 0, bottom: 6.9, right: 0)
//        layout.sectionInset = UIEdgeInsets(top: 12.5, left: 0, bottom: 12.5, right: 0)
//        layout.scrollDirection = .Horizontal
//        let cv = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
//        return cv
//    }()
    
    
    init(callBack: (EmoticonModel) -> ()) {
        self.callBack = callBack
        let rect = CGRect(x: 0, y: 0, width: 0, height: 226)
        super.init(frame: rect)
        backgroundColor = UIColor.darkGrayColor()
        setupUI()
//        print(packages())
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        addSubview(bottomBar)
        addSubview(emoticonList)
        prepareToolBar()
        prepareCollection()

        //设置布局
        bottomBar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(self.snp_bottom)
            make.left.equalTo(self.snp_left)
            make.right.equalTo(self.snp_right)
            make.height.equalTo(40)
        }
        
        emoticonList.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_top)
            make.left.equalTo(self.snp_left)
            make.right.equalTo(self.snp_right)
            make.bottom.equalTo(bottomBar.snp_top)
        }
    }
    
    //MARK: toobar相关
    private func prepareToolBar() {
        
//        let titleArray = ["最近", "默认", "employ", "浪小花" ]
        var barBtnS = [UIBarButtonItem]()
        var index  =  0
        for i in packages {
            let barButton = UIBarButtonItem(title: i.group_name_cn, style: UIBarButtonItemStyle.Done, target: self, action: "clickButton:")
            //加入弹簧的btn
            barButton.tag = index
            index++
            let bounsButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
            barBtnS.append(barButton)
            barBtnS.append(bounsButton)
        }
        barBtnS.removeLast()
        bottomBar.tintColor = UIColor.blackColor()
        bottomBar.items = barBtnS
    }
    
    @objc func clickButton(sender: UIBarButtonItem) {
        let indexpath = NSIndexPath(forRow: 0, inSection: sender.tag)
        
        emoticonList.scrollToItemAtIndexPath(indexpath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: true)
    }
    
    private func prepareCollection() {
        
        emoticonList.backgroundColor  = UIColor.lightGrayColor()
        //设置数据源
        emoticonList.dataSource = self
        emoticonList.delegate = self
        emoticonList.registerClass(EmoticonCell.self, forCellWithReuseIdentifier: ReuseCollectionCellID)
    
        
    }
    class emoticonLayout: UICollectionViewFlowLayout {
        override func prepareLayout() {
            super.prepareLayout()
    
//            let layout = UICollectionViewFlowLayout()
            let row: CGFloat = 3
            let col: CGFloat = 7
            minimumLineSpacing = 0
            minimumInteritemSpacing = 0
            let w = UIScreen.mainScreen().bounds.width / col
            itemSize = CGSize(width: w, height: w)
            let margin = ((collectionView?.bounds.height)! - row * w) * 0.4999
    //        UIEdgeInsets(top: 6.9, left: 0, bottom: 6.9, right: 0)
            sectionInset = UIEdgeInsets(top: margin, left: 0, bottom: margin, right: 0)
//            sectionInset = UIEdgeInsets(top: 12.5, left: 0, bottom: 12.5, right: 0)
            scrollDirection = .Horizontal
            collectionView?.pagingEnabled = true
            collectionView?.bounces = false
            collectionView?.showsHorizontalScrollIndicator = false
        }
    }
}

//collention相关
extension EmoticonView: UICollectionViewDataSource, UICollectionViewDelegate {
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return packages.count
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return packages[section].emoticons.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ReuseCollectionCellID, forIndexPath: indexPath) as! EmoticonCell
////        let imageName = packages.emoticonList[indexPath.section].emoticons![indexPath.item].pngPath ?? ""
//        let imgView = UIImageView(image: UIImage(named: imageName))
//        cell.contentView.addSubview(imgView)
        cell.backgroundColor = UIColor.lightGrayColor()
        cell.emoticonModel = packages[indexPath.section].emoticons[indexPath.item]
        return cell
    }
    
    //获取随机颜色的方法
    private func randomColor() -> UIColor {
        let r = CGFloat(random()%255)/255.0
        let g = CGFloat(random()%255)/255.0
        let b = CGFloat(random()%255)/255.0
        return UIColor(red: r, green: g, blue: b, alpha: 1)
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let emoticonModel = EmoticonManager.sharedManager.emoticonList[indexPath.section].emoticons[indexPath.item]
//        print("选中了" + "\(emoticonModel)")
        self.callBack(emoticonModel)
    }
}

extension EmoticonView {

    class EmoticonCell: UICollectionViewCell {
        
        private var emoticonModel: EmoticonModel? {
            didSet {
                let file = emoticonModel?.pngPath
                let img = UIImage(contentsOfFile: file ?? "")
                cellButton.setImage(img, forState: UIControlState.Normal)
                cellButton.setTitle(emoticonModel!.emoji ?? "", forState: .Normal)
                
                if emoticonModel?.isRemoved == true {
                    cellButton.setImage(UIImage(named: "compose_emotion_delete_highlighted-1"), forState: UIControlState.Normal)
                }
            }
        }
        
        private lazy var cellButton: UIButton = UIButton()
        
        override init(frame: CGRect) {
            super.init(frame: frame)
            setupCellUI()
        }

        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
        
        private func setupCellUI() {
            contentView.addSubview(cellButton)
            cellButton.backgroundColor = UIColor.init(white: 0.8, alpha: 1)
            cellButton.frame = CGRectInset(bounds, 4, 4)
            
            cellButton.titleLabel?.font = UIFont.systemFontOfSize(32)
            cellButton.userInteractionEnabled = false
        }
    }
}